package com.xsz.service;

import com.xsz.entity.Administrator;
import com.xsz.entity.Administrator;
import com.xsz.entity.User;
import com.xsz.repository.AdministratorRepository;
import com.xsz.repository.UserRepository;
import com.xsz.util.MD5Utils;
import org.springframework.stereotype.Service;
import com.xsz.util.KeyUtil;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AdministratorService {
    @Resource
    AdministratorRepository administratorRepository;

    @Resource
    UserRepository userRepository;

    @Resource
    RedisTemplateService redisTemplateService;

    //新建管理员
    public Administrator add(Administrator administrator){
        administrator.setId(KeyUtil.getId());
        return administratorRepository.save(administrator);
    }

    //修改管理员信息
    public Administrator update(Administrator administrator) {
        return administratorRepository.save(administrator);
    }


    //根据id删除管理员信息
    public void delete(String id) {
        administratorRepository.deleteById(id);
    }

    //根据id查询管理员信息
    public Administrator selectById(String id) {
        return administratorRepository.findById(id).get();
    }

    //根据账号查询管理员信息
    public Administrator getByName(String name) {
        return administratorRepository.findByName(name);
    }

    //查询所有用户
    public List<User> getAllUser() {
        return userRepository.findAll();
    }

    //根据用户账号查询用户
    public User getByUserName(String name) { return userRepository.findByName(name); }

    //根据用户账号关键字查询用户
    public List<User> getByUserLikeName(String name) {return userRepository.findByNameLike("%"+name+"%"); }

    //重置密码
    public void updatepwd(String name) {
        String pwd = MD5Utils.encrypt(name, "123456");
        administratorRepository.updatepwd(pwd,name);
    }

    //根据用户账号关键字查询用户
    public List<User> getByRole() {
        return userRepository.findByRole(2);
    }

    //批准申请VIP用户
    public void updaterole(String id) {
        int rsint= administratorRepository.updaterole(1,id);
        if(rsint>0) {
            User user = redisTemplateService.get(id+"login",User.class);
            user.setRole(1);
            redisTemplateService.set(user.getId()+"login",user);
        }
    }
}
